﻿using CommunityToolkit.Mvvm.Input;
using HandyControl.Data;
using Koala.Pro.Common;
using Koala.Pro.Common.Extension;
using Koala.Pro.Core.Dto;
using Koala.Pro.Core.Models;
using Koala.Pro.Helpers;
using Koala.Pro.Models;
using Koala.Pro.Services;
using Koala.Pro.ViewModels;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Wpf.Ui.Controls;

namespace Koala.Pro.Views.Pages
{
    public partial class FunctionListPage : Page, INavigableView<FunctionListViewModel>
    {
        public FunctionListViewModel ViewModel { get; }

        public FunctionListPage(FunctionListViewModel viewModel)
        {
            ViewModel = viewModel;
            base.DataContext = this;
            InitializeComponent();
            ViewModel.GetTreeCommand.ExecuteAsync(null);
            ViewModel.PageDto.SystemType_ID = App.ViewModel.SystemType;
        }

        [RelayCommand]
        private async Task BatchAdd()
        {
            FunctionBatchAddPage service = App.GetService<FunctionBatchAddPage>();
            service.ViewModel.Item = new BatchAddFunctionDto
            {
                PID = (ViewModel.PageDto.PID ?? "-1"),
                SystemType_ID = App.ViewModel.SystemType,
                SubFunctions = service.ViewModel.SubFunctions.Select((CListItem s) => s.Text).ToList()
            };
            service.ShowDialog();
            FunctionBatchAddViewModel viewModel = service.ViewModel;
            if (viewModel != null && viewModel.Result?.Success == true)
            {
                await ViewModel.GetData();
                await ViewModel.GetTreeCommand.ExecuteAsync(null);
            }
        }

        [RelayCommand]
        private async Task Add()
        {
            await Edit(null);
        }

        [RelayCommand]
        private async Task EditById(string id)
        {
            if (!id.IsNullOrEmpty())
            {
                FunctionEditPage page = App.GetService<FunctionEditPage>();
                FunctionEditViewModel viewModel = page.ViewModel;
                viewModel.Item = await BLLFactory<IFunctionService>.Instance.GetAsync(id);
                await page.ViewModel.InitData(id);
                page.ViewModel.IsEdit = true;
                page.ShowDialog();
                FunctionEditViewModel viewModel2 = page.ViewModel;
                if (viewModel2 != null && viewModel2.Result?.Success == true)
                {
                    await ViewModel.GetData();
                    await ViewModel.GetTreeCommand.ExecuteAsync(null);
                }
            }
        }

        [RelayCommand]
        private async Task Edit(FunctionInfo info)
        {
            FunctionEditPage page = App.GetService<FunctionEditPage>();
            if (info != null)
            {
                FunctionEditViewModel viewModel = page.ViewModel;
                viewModel.Item = await BLLFactory<IFunctionService>.Instance.GetAsync(info.Id);
                await page.ViewModel.InitData(info.Id);
                page.ViewModel.IsEdit = true;
                page.Height = 480.0;
                page.Width = 720.0;
            }
            else
            {
                long num = 0L;
                if (!ViewModel.PageDto.PID.IsNullOrEmpty())
                {
                    num = await BLLFactory<IFunctionService>.Instance.CountAsync((FunctionInfo s) => s.PID == ViewModel.PageDto.PID);
                }
                page.ViewModel.Item = new FunctionInfo
                {
                    PID = ViewModel.PageDto.PID,
                    SortCode = (num + 1).ToString("D3"),
                    SystemType_ID = App.ViewModel.SystemType
                };
                page.ViewModel.RoleInfos.Clear();
                page.ViewModel.IsEdit = false;
                page.Height = 450.0;
                page.Width = 540.0;
            }
            page.ShowDialog();
           
            if (page.ViewModel.Result?.Success == true)
            {
                await ViewModel.GetData();
                await ViewModel.GetTreeCommand.ExecuteAsync(null);
            }
        }

        [RelayCommand]
        private async Task Delete(FunctionInfo info)
        {
            await ViewModel.DeleteCommand.ExecuteAsync(info);
            await ViewModel.GetData();
            await ViewModel.GetTreeCommand.ExecuteAsync(null);
        }

        [RelayCommand]
        private void Search()
        {
            ViewModel.PageDto.PID = null;
            ViewModel.SearchCommand.ExecuteAsync(null);
        }

        private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!(sender is System.Windows.Controls.DataGrid { SelectedItems: var selectedItems }))
            {
                return;
            }
            if (selectedItems != null)
            {
                List<FunctionInfo> list = new List<FunctionInfo>();
                foreach (FunctionInfo item in selectedItems)
                {
                    list.Add(item);
                }
                ViewModel.SelectedItems = list;
            }
            else
            {
                ViewModel.SelectedItems = null;
            }
        }

        [RelayCommand]
        private void ImportExcel()
        {
            var importPage = App.GetService<ImportExcelPage>();
            importPage.ViewModel.Items?.Clear();
            importPage.ViewModel.TemplateFile = "系统功能定义-模板.xls";
            importPage.OnDataSave -= ExcelData_OnDataSave;
            importPage.OnDataSave += ExcelData_OnDataSave;
            ViewModel.Navigate(typeof(ImportExcelPage));
        }

        private string GetRowData(DataRow row, string columnName)
        {
            string result = "";
            if (row.Table.Columns.Contains(columnName))
            {
                result = row[columnName].ToString();
            }
            return result;
        }

        private async Task<bool> ExcelData_OnDataSave(DataRow dr)
        {
            FunctionInfo functionInfo = new FunctionInfo();
            functionInfo.PID = GetRowData(dr, "父ID");
            functionInfo.Name = GetRowData(dr, "功能名称");
            functionInfo.ControlID = GetRowData(dr, "权限标识");
            functionInfo.SystemType_ID = GetRowData(dr, "系统编号");
            functionInfo.SortCode = GetRowData(dr, "排序码");
            return await BLLFactory<IFunctionService>.Instance.InsertAsync(functionInfo);
        }

        private async void function_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (e.NewValue is CustomTreeNode customTreeNode)
            {
                ViewModel.FunctionTreeModel.SelectNode = customTreeNode;
                ViewModel.PageDto.PID = customTreeNode.Id;
                await ViewModel.GetData();
            }
        }

        private void SearchBar_OnSearchStarted(object sender, FunctionEventArgs<string> e)
        {
            ViewModel.FunctionTreeModel.SearchKey = e.Info;
            if (e.Info.IsNullOrEmpty())
            {
                ViewModel.FunctionTreeModel.FilteredTreeItems = ViewModel.FunctionTreeModel.TreeItems;
                return;
            }
            ViewModel.FunctionTreeModel.FilteredTreeItems = ViewModel.FunctionTreeModel.TreeItems.FindCustomNodes((CustomTreeNode s) => s.Name.Contains(e.Info, StringComparison.OrdinalIgnoreCase));
        }

        private async void function_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (functionTree.SelectedItem is CustomTreeNode customTreeNode)
            {
                FunctionInfo functionInfo = await BLLFactory<IFunctionService>.Instance.GetAsync(customTreeNode.Id);
                if (functionInfo != null)
                {
                    await Edit(functionInfo);
                }
            }
        }
    }
}
